/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PLan.java
 *
 * Created on 2010-feb-02, 18:57:31
 */
package exmtgproj;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.JOptionPane;

/**
 * Klass för spelplana som håller reda på vilka kort som ska visas var och
 * skickar  info till Preview om viket kort användaren hoverar över
 * @author marcus ahlen
 */
public class SpelPlan extends javax.swing.JPanel implements Statics {

    static int yPix = 0;
    static int yPrev = 0;
    static int x = 0;   //kolumn på skärmen
    static int z = 0;   //NYI djup, kort som är kopplade till andra kort (till spelet)
    static int zx = 0;  //NYI bläddring mellan korten som är kopplade till andra kort
    static double markSize = 1.1;  //hur många procent highlighting ska sticka ut utanför kortet också mellanrum mellan korten, kan inte vara 0, ska helst vara >= 1
    static int cardsPerRow = 7;  //antalet kort som ska finnas på en rad
    static int cardWidth = 0; //bredden på korten
    static int cardHeight = 0; //höjden på korten
    static int cardSpace = 0; //storleken på mellanrummet mellan korten
    static int highlight = -1;  //vilket kort som är highlightat

    /**
     * uppdaterar dimensionerna på korten (om fönstret ändrat storlek)
     */
    private void updateCardDimensions() {
        cardWidth = (int) (getWidth() / (cardsPerRow * markSize));
        cardHeight = cardWidth * 17 / 12;
        cardSpace = (int) (cardWidth * markSize - cardWidth);
        yPix = 0;
        repaint();
    }

    public void setNewCardDimensions(int cpr) {
        cardsPerRow = cpr;
        updateCardDimensions();
    }

    /**
     * Returnerar det kort som musen hovrar över
     * @param x musens position i x
     * @param y musens position i y
     * @return det kort som musen hovrar över
     */
    private Card cardAt(int x, int y) {
        x /= (cardWidth + cardSpace + 1);   //ränkar ut vilken column kortet ligger på
        y -= yPix;  //tar bort skillnaden som blivit av att skärmen har dragits ned
        y /= (cardHeight + cardSpace + 1);  //ränkar ut vilken rad kortet ligger på
        int c = x + y * cardsPerRow;    //räknar ut vilket index kortet ligger på
        if (MainFrame.chosenDeck != null && MainFrame.chosenDeck.size() > c) { //om kortet går att hitta
            highlight = c;  //highighta kortet
            return MainFrame.chosenDeck.get(c); //returnera kortet
        } else {
            return null;
        }
    }

    /** Creates new form PLan */
    public SpelPlan() {
        initComponents();
    }

    /*
    void randomColor() {
    String[] color = {"W", "U", "B", "R", "G"};
    int a = (int) (Math.random() * 5);
    int b = (int) (Math.random() * 5);
    if (a == b) {
    bg = Images.getImage(color[a]);
    } else if (a < b) {
    bg = Images.getImage(color[a] + color[b]);
    } else {
    bg = Images.getImage(color[b] + color[a]);
    }
    a = (int) (Math.random() * 5);
    b = (int) (Math.random() * 5);
    if (a == b) {
    bg2 = Images.getImage(color[a]);
    } else if (a < b) {
    bg2 = Images.getImage(color[a] + color[b]);
    } else {
    bg2 = Images.getImage(color[b] + color[a]);
    }
    }
    Image bg = Images.getImage("B");
    Image bg2 = Images.getImage("R");
     */
    @Override
    public void paint(Graphics g) {
        g.setColor(Color.gray);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.black);
        try {
            for (int i = 0; i < /*Game.getCurrentPlayer().zone[deck]*/ MainFrame.chosenDeck.size() && i < (1 + (getHeight() - yPix) / cardHeight) * cardsPerRow; i++) {
                MainFrame.chosenDeck.get(i).draw(g, /*Game.getCurrentPlayer().zone[deck]*/ createCardBoundsInPreviewDeckView(i), highlight == i);
            }
        } catch (Exception e) {
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(506, 506));
        setPreferredSize(new java.awt.Dimension(506, 506));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 506, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 506, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        Card c = cardAt(evt.getX(), evt.getY());
        if (c == null) {
            return;
        }
        if (evt.getButton() == 1) {
            c.facedown = !c.facedown;
        }
        if (evt.getButton() == 3) {
            c.marked = !c.marked;
        }
        repaint();
        MainFrame.prev.repaint();
    }//GEN-LAST:event_formMouseClicked

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        System.out.println("drd");
    }//GEN-LAST:event_formKeyPressed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        updateCardDimensions();
    }//GEN-LAST:event_formComponentResized

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
    }//GEN-LAST:event_formMouseMoved

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
        if (MainFrame.chosenDeck == null) {
            return;
        }
        double tes = (double) /*Game.getCurrentPlayer().zone[deck]*/ MainFrame.chosenDeck.size() / (double) cardsPerRow;
        if (tes % 1 != 0) {
            tes++;
        }
        int min = -(int) (Math.floor(tes) * (cardHeight + cardSpace) - getHeight());
        int max = 0;
        int change = evt.getY() - yPrev;
        yPix += change;
        yPix = Math.max(Math.min(yPix, max), min);
        yPrev = evt.getY();
        repaint();
    }//GEN-LAST:event_formMouseDragged

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        yPrev = evt.getY();
    }//GEN-LAST:event_formMousePressed

    private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
    }//GEN-LAST:event_formMouseReleased
    public void mouseMoved(int x, int y) {
        Preview.prevCard = cardAt(x, y);
        if (Preview.prevCard != Preview.prevPrevCard) {
            repaint();
        }
        MainFrame.prev.repaint();

    }

    /**
     *
     * @param key
     * @param modifier
     */
    public void keyPressed(int key, int modifier) {
        System.out.println(key + " " + modifier);
        if (key == 70 && modifier == 2 || true) {
            if (MainFrame.chosenDeck == null) {
                return;
            }
            String search = JOptionPane.showInputDialog("Search facedown cards for:\n(To not shuffle type a '!' somewhere in the text\n For exact search type '\"')");
            if (search == null) {
                return;
            }
            boolean shuffle = !search.contains("!");
            search.replace('!', ' ');
            CardList cl1 = new CardList();
            CardList cl2 = new CardList();
            for (Card zkard : MainFrame.chosenDeck) {
                if (!zkard.marked || !zkard.facedown) {
                    cl1.add(zkard);
                } else {
                    cl2.add(zkard);
                }
            }
            Card c = cl2.search(search);
            cl1.sort(CardList.sort[CardList.MARKED], CardList.sort[CardList.FACEDOWN], CardList.sort[CardList.TYPE], CardList.sort[CardList.RARITY], CardList.sort[CardList.NAME]);
            if (shuffle) {
                cl2.shuffle();
            }
            if (c != null) {
                cl2.remove(c);
                c.facedown = false;
                cl1.add(c);
            }
            for (Card zkard : cl2) {
                cl1.add(zkard);
            }
            MainFrame.chosenDeck = cl1;
        }
    }

    public void keyReleased(int key, int modifier) {
    }

    public void keyTyped(int key, int modifier) {
    }

    private void drawCard(Graphics g, Card c, int x, int y) {
    }

    private void drawHand(Graphics g) {
    }

    private int cardPositionX(int index) {
        return index % cardsPerRow;
    }

    private int cardPositionY(int index) {
        return index / cardsPerRow;
    }

    /**
     * Ritar ett kort
     * @param g grafik objectet som ska användas för utritningen
     * @param c kortet som ska ritas
     * @param i indexet för kortet
     */
    private void drawCard(Graphics g, Card c, int i) {
    }

    private Rectangle createCardBoundsInPreviewDeckView(int i) {
        int cardX = cardSpace / 2 + cardPositionX(i) * (cardWidth + cardSpace);
        int cardY = cardSpace / 2 + cardPositionY(i) * (cardHeight + cardSpace) + yPix; //0 = yy
        return new Rectangle(cardX, cardY, cardWidth, cardHeight);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
